<?php
require_once APPLICATION_PATH . "/modules/event/models/ModelBase.php";

class Comment extends TTEvent_Table_Abstract
{
    protected $_name = 'tamtay_comment';
    
	
	public function getEventComment($ref, $totalComment, $page=0){	
		$sql="SELECT c.*, u.name, u.avatar
			FROM tamtay_comment c INNER JOIN users u ON c.uid=u.uid
			WHERE c.ref=? AND c.module='event' ORDER BY created DESC";
			
		return $this->pageQuery($sql, array($ref), $page, $totalComment);
	}
	
	public function getEventComments($ref, $page=0, $limit=20)
    {
    	$ref = (int)$ref;
		$from=$page*EVENT_COMMENT_PER_PAGE;        
		$sql="SELECT c.*, u.avatar FROM tamtay_comment c LEFT JOIN users u ON c.uid = u.uid WHERE c.ref=$ref AND c.reply_to=0 AND c.module='event' ORDER BY changed DESC, created DESC LIMIT $from, $limit";		
		$db=$this->getSlaveDB();
		$stm=$db->query($sql);
		$data=array();
		while ($c=$stm->fetch())
		{
			$data[]=$c;
		}
		return $data;
	}
	
	public function getReplies($cids)
    {
        if (count($cids) < 1) {
            return FALSE;
        }
        $i = 0;
        $in = '';
        $ret = array();
        foreach ($cids as $cid) {
           $ret[$cid] = array();
            if ($i == 0) {
                $in = '(' . "'$cid'";
            } else {
                $in .= ',' . "'$cid'";
            }
            $i++;
        }
        $in .= ')';
        $db = $this->getSlaveDB();
        $sql = "SELECT c.*, u.avatar FROM tamtay_comment c LEFT JOIN users u ON c.uid = u.uid WHERE  c.module='event' AND reply_to IN $in ORDER BY cid, created"; 
        $stm = $db->query($sql);       
        while ($c = $stm->fetch()) {
            $ret[$c->reply_to][] = $c;        
        }
        return $ret;
    }
    
	public function getEventCommentCount($eid)
    {
        $sql="SELECT comment_count FROM tamtay_event WHERE eid=$eid";
        $db=$this->getSlaveDB();
        $c=$db->fetchOne($sql);
        return $c;
    }
    
	public function getEventReplyCount($eid)
    {
    	$eid = (int)$eid;
        $sql="SELECT reply_count FROM tamtay_event WHERE eid=$eid";
        $db=$this->getSlaveDB();
        $c=$db->fetchOne($sql);
        return $c;
    }
    
	public function updateCommentChanged($cid)
    {           
        $data = array('changed' => time());
        $this->update($data, "cid = '$cid'");
    }
    
	public function getEventInfoFromComment($cid)
	{
		$sql="SELECT e.* FROM tamtay_event e INNER JOIN tamtay_comment c ON e.eid=c.ref WHERE c.cid=?";
		$db=$this->getSlaveDB();
		$stm=$db->query($sql, $cid);
		if ($event=$stm->fetch())
		{
			return $event;
		}
		return false;
	}
	
	public function deleteComment($cid, $ref, $isReply = FALSE)
	{
		$db=$this->getMasterDB();
		$sql="DELETE FROM tamtay_comment WHERE cid=" . $cid;
		$db->query($sql);
		
		if ( ! $isReply) {
            $sql="DELETE FROM tamtay_comment WHERE module='event' AND reply_to=" . $cid;
            $db->query($sql);        
        }
        
        $sql = "SELECT COUNT(*) FROM tamtay_comment WHERE module='event' AND ref = ? AND reply_to != ?";
        $reply_count=$db->fetchOne($sql, array($ref, 0));                  
        $sql = 'UPDATE tamtay_event SET reply_count = ? WHERE eid = ?';
        $db->query($sql, array($reply_count, $ref));
		
		$sql="SELECT COUNT(*) FROM tamtay_comment WHERE ref=" . $ref;
		$comment_count=$db->fetchOne($sql);
		
		$sql="UPDATE tamtay_event SET comment_count=" . $comment_count . " WHERE eid=" . $ref;
		$db->query($sql);
		return $comment_count;
	}
	
	
	public function insertComment($data)
	{
		$this->insert($data);
		$cid=$this->getDefaultAdapter()->lastInsertId();
		
		$sql="SELECT COUNT(*) FROM tamtay_comment WHERE ref=" . $data["ref"];
		$db=$this->getMasterDB();
		$comment_count=$db->fetchOne($sql);
		$sql="UPDATE tamtay_event SET comment_count=" . $comment_count . " WHERE eid=" . $data["ref"];
		$db->query($sql);
		if ($data['reply_to'] != 0) {
            $sql = 'SELECT COUNT(*) FROM tamtay_comment WHERE ref = ? AND reply_to != ?';
            $db = $this->getMasterDB();
            $reply_count = $db->fetchOne($sql, array($data['ref'], 0));
            $sql = 'UPDATE tamtay_event SET reply_count = ? WHERE eid = ?';    
            $db->query($sql, array($reply_count, $data['ref']));
        }
		return $cid;
	}
	
	public function loadAllComment($search, $page, $limit=30)
	{
		$sql="SELECT c.*, a.title FROM tamtay_comment c INNER JOIN event a ON c.ref=a.ref";
		$sql_count="SELECT COUNT(*) FROM tamtay_comment c INNER JOIN event a ON c.ref=a.ref";
		$cond="";
		$param=array();
		if ($search['user']!="")
		{
			$param[]=$search['user'];
			$cond="c.uname=?";
		}
		if ($search['title']!="")
		{
			$param[]='%' . $search['title'] . '%';
			if ($cond!="")
			{
				$cond=$cond . " AND ";
			}
			$cond=$cond . "a.title LIKE ?";
		}
		if ($search['comment']!="")
		{
			$param[]='%' . $search['comment'] . '%';
			if ($cond!="")
			{
				$cond=$cond . " AND ";
			}
			$cond=$cond . "c.content LIKE ?";
		}
		if ($search['fromDate']!="")
		{
			$format = '%d/%m/%Y';
			$from=strptime($search['fromDate'], $format);
			if ($from)
			{
				$from=mktime(0, 0, 0, $from["tm_mon"] + 1, $from["tm_mday"], $from["tm_year"] + 1900);
			}
			if ($from)
			{
				$param[]=$from;
				if ($cond!="")
				{
					$cond=$cond . " AND ";
				}
				$cond=$cond . "c.created >= ?";
			}
		}
		if ($cond!="")
		{
			$sql=$sql . " WHERE " . $cond;
			$sql_count=$sql_count . " WHERE " . $cond;
		}
		
		$sql=$sql . " ORDER BY c.created DESC";
		
		$this->setRowPerPage($limit);
		return $this->pageQuery($sql, $param, $page, $sql_count);
	}
	
	public function updateComment($cid, $comment)
	{
		$db=$this->getMasterDB();
		$sql="UPDATE tamtay_comment SET content=? WHERE cid=?";
		$db->query($sql, array($comment, $cid));
	}
    
    public function getComment($cid, $module="")
    {
        $db=$this->getSlaveDB();
        $sql="SELECT * FROM tamtay_comment WHERE cid=?";
        if($module)
        	$sql = $sql ." AND module='".$module."'";
        $stm=$db->query($sql, $cid);
        $c=$stm->fetch();
        return $c;
    }
}

